import React from 'react';
import { useEffect, useState } from 'react'
import axios from 'axios';
import { StarOutlined, StarFilled } from '@ant-design/icons';
import { useParams } from "react-router-dom";
import { useNavigate } from 'react-router-dom'
const StarRating = () => {
  let { id } = useParams(); 
  const [rating, setRating] = useState(null);
  const [hover, setHover] = useState(null);
  const [numOfRatings, setNumOfRatings] = useState(0);
  const [averageScore, setAverageScore] = useState(null);

  useEffect(() => {
    const studentid = localStorage.getItem('studentid');
    const courseid = id;
    axios.post('http://localhost:8000/getcoursescore', { courseid: courseid, studentid: studentid })
    .then(response => {
      // 处理从后端返回的数据

      // 计算有评分的学生评分平均值和人数
      if (response.data.results2 && response.data.results2.length > 0) {
        const ratings = response.data.results2.filter(item => item.score !== null);
        const totalNumOfRatings = ratings.length;
        setNumOfRatings(totalNumOfRatings);

        if (totalNumOfRatings > 0) {
          const totalScore = ratings.reduce((acc, cur) => acc + parseInt(cur.score), 0);
          const avgScore = totalScore / totalNumOfRatings;
          setAverageScore(avgScore.toFixed(2));
        }
      }

      // 设置星星数量的初状态为学生评分（如果有评分）
      if (response.data.results1 && response.data.results1.length > 0) {
        setRating(parseInt(response.data.results1[0].score));
      }
    })
    .catch(error => {
      console.error('Error:', error);
    });
  }, [rating]);

  const handleRating = (value) => {
    const studentid = localStorage.getItem('studentid');
    const courseid = id;
    axios.post('http://localhost:8000/uploadcoursescore', { studentid, courseid, value })
    .then(response => {

    })
    .catch(error => {
      console.error('Error:', error);
    });
    setRating(value);
};

  return (
    <div>
      {[...Array(5)].map((_, index) => {
        const starValue = index + 1;
        return (
          <span
            key={starValue}
            onClick={() => handleRating(starValue)}
            onMouseEnter={() => setHover(starValue)}
            onMouseLeave={() => setHover(null)}
          >
            {starValue <= (hover || rating) ? (
              <StarFilled style={{ fontSize: '20px', color: '#FFC107' }} />
            ) : (
              <StarOutlined style={{ fontSize: '20px', color: '#e4e5e9' }} />
            )}
          </span>
        );
      })}
      {averageScore && <p>总评价人数: {numOfRatings},平均评分: {averageScore}</p>}
    </div>
  );
};

export default StarRating;
